package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.mall.lib.dto.MerchantShoppingCartDto;
import com.rockcent.mall.lib.dto.ShoppingCartDto;
import com.rockcent.mall.lib.dto.ShoppingCartProductDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;

/**
 * Created by zhangjh on 2016/10/12.
 */
@Repository
public class ShoppingCartRepositoryImpl implements ShoppingCartRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(ShoppingCartRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
   public Integer deleteByCustomerIdAndProductIds(Long customerId, List<Long> productIds){
        HashMap params = new HashMap<>();
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM shopping_cart WHERE customer_id=:customerId ");
        if (productIds != null && productIds.size() >0 ){
            sql.append(" AND product_id IN(:productIds) ");
            params.put("productIds", productIds);
        }
        params.put("customerId",customerId);
        return jdbcTemplate.update(sql.toString(),params);
    }

    public List<MerchantShoppingCartDto> getShoppingCart(Long customerId){
        SQLListDoing<MerchantShoppingCartDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT * FROM shopping_cart sc LEFT JOIN product p ON sc.product_id = p.id WHERE sc.customer_id =:customerId order by sc.date_created desc");
            params.put("customerId",customerId);
        };
        return doing.go(MerchantShoppingCartDto.class, jdbcTemplate, log,objectMapper);
    }
    public List<ShoppingCartProductDto> getProduct(Long customerId, Long merchantId){
        SQLListDoing<ShoppingCartProductDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT * FROM shopping_cart sc LEFT JOIN product p ON sc.`product_id` = p.`id` WHERE sc.`customer_id`=:customerId and p.`merchant_id`=:merchantId;");
            params.put("customerId",customerId);
            params.put("merchantId",merchantId);
        };
        return doing.go(ShoppingCartProductDto.class, jdbcTemplate, log,objectMapper);
    }


}
